package edu.ptu.communityplatform.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import edu.ptu.communityplatform.domain.entity.User;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

/**
 * @BelongsProject: communityPlatform
 * @BelongsPackage: edu.ptu.communityplatform.utils
 * @Author: HYJ
 * @CreateTime: 2025-04-05  00:01
 * @Description: TODO
 * @Version: 1.0
 */
public class JWTUtil {
    public static final String SECRET_KEY = "communityPlatform";

    public static final String USER_ID = "userId";

    public static final String USER_NAME = "userName";

    public static final Integer EXPIRATION_TIME = 1;

    /**
     * @description: 生成token
     * @author: HYJ
     * @date: 2025/4/5 0:01
     * @param: [user]
     * @return: java.lang.String
     **/
    public static String createToken(User user) {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, EXPIRATION_TIME);

        return JWT.create()
                .withClaim(USER_ID, user.getUserId())
                .withClaim(USER_NAME, user.getUserName())
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET_KEY));
    }

    /**
     * @description: 验证token
     * @author: HYJ
     * @date: 2025/4/5 0:01
     * @param: [token]
     * @return: boolean
     **/
    public static boolean verifyToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET_KEY)).build().verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @description: 获取用户ID
     * @author: HYJ
     * @date: 2025/4/5 0:01
     * @param: [request]
     * @return: java.lang.String
     **/
    public static String getUserName(HttpServletRequest request) {
        return JWT.decode(request.getHeader("token")).getClaim(USER_NAME).asString();
    }

    /**
     * @description: 获取用户ID
     * @author: HYJ
     * @date: 2025/4/5 0:01
     * @param: [request]
     * @return: java.lang.Long
     **/
    public static Long getUserId(HttpServletRequest request) {
        return JWT.decode(request.getHeader("token")).getClaim(USER_ID).asLong();
    }
}
